import { Flex, FloatButton, Typography } from "antd";
import { useCallback, useEffect, useReducer, useState } from "react";
import { DownloadOutlined, MenuOutlined, SettingOutlined } from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
import DownloadForm, { FormData } from "../../containers/DownloadForm";
import emitInstance from "../../eventEmitter"
import getBook from "../../services/getBook";
import styled from "styled-components";
import DownloadDrawer from "../../containers/DownloadDrawer";
import { Store } from "../../store";
import { useSelector, useDispatch } from "react-redux";
const { Group } = FloatButton;
const Wrap = styled.div`
    padding: 15px;
`
const TextView = styled.div`
    white-space: pre-wrap;
`
const Main = () => {
    const [complateCount, setComplateCount] = useState({
        success: 0,
        fail: 0
    });
    const [activeChapter, setActiveChapter] = useState('');
    const [filstChapter, setFirstChapter] = useState('');
    const [lock, setLock] = useState(false);
    const [fileData, setFileData] = useState({
        name: '',
        path: '',
    })
    const navigate = useNavigate()
    const goRoute = useCallback((route:string) => {
        navigate(route);
    }, [navigate])
    const addComplateCount = (status:boolean) => {

        setComplateCount(obj => {
            const activeKey = status ? 'success' : 'fail';
            return {
                ...obj,
                [activeKey]: obj[activeKey] + 1
            }
        })
    }
    const setActive = (str:string) => {
        setActiveChapter(str)
    }
    const download = async (data:FormData) => {
        // console.log('download----');
        // setLock(true);
        const its = getBook(data.firstUrl, {
            chapterNameSelecter: data.titleSelecter,
            chapterContentSelecter: data.contentSelecter,
            nextChapterSelecter: data.nextSelecter
        });
        const { value: firstChapter } = await its.next();
        console.log('firstChapter====', firstChapter);

        setFirstChapter(firstChapter);

        const { value: text } = await its.next(true);
        if (!text) {
            setLock(false);
            return;
        }
        const writeRes = await window.electron.writeFile(data.bookName + '.txt', text);
        setFileData({
            name: data.bookName + '.txt',
            path: writeRes.filePath,
        })
        setLock(false);
    }
    const onSubmit = useCallback((data:FormData) => {
        if (lock) return;
        download(data);
    }, [lock])
    useEffect(() => {
        emitInstance.addListener('__add_complate_count__', addComplateCount);
        emitInstance.addListener('__set_active_chapter__', setActive);
        return () => {
            emitInstance.removeListener('__add_complate_count__', addComplateCount);
            emitInstance.removeListener('__set_active_chapter__', setActive);
        }
    }, [])
    const dispatch = useDispatch()
    const click = useCallback(() => {
        dispatch({
            type: 'AAA',
            payload: '666'
        })
    }, [dispatch])
    const login = useSelector((state: Store) => state.login)
    return <Wrap >
        <Flex vertical gap={15}>
            <div onClick={click}>点击</div>
            {
                login
            }
            <Flex justify="space-between" style={{ padding: 10 }}>
                <Typography.Title level={4}>爬行者-T900</Typography.Title>
            </Flex>
            <DownloadForm onSubmit={onSubmit} />
            {filstChapter && <Typography.Text>
                <div>第一页预览：</div>
                <br />
                <TextView dangerouslySetInnerHTML={{ __html: filstChapter }} />
            </Typography.Text>}
        </Flex>
        <DownloadDrawer
            complateCount={complateCount}
            active={activeChapter}
            bookName={fileData.name}
            filePath={fileData.path}
        />
        <Group
            trigger="click"
            placement="top"
            badge={{
                dot: true
            }}
            icon={<MenuOutlined />}
        >
            <FloatButton
                badge={{
                    count: 6,
                    overflowCount: 99,
                }}
                icon={<DownloadOutlined />}
                onClick={goRoute.bind(null, '/download')}
            />
            <FloatButton
                badge={{
                    count: 6,
                    overflowCount: 99,
                }}
                icon={<SettingOutlined />}
                onClick={goRoute.bind(null, '/setting')}
            />
        </Group>

    </Wrap>
}

export default Main;

